<script setup lang="ts">
import { Form } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, ref, watch } from 'vue'
import { FormSchema } from '@/types/form'
import { ElTable, ElTableColumn, ElInput, ElButton } from "element-plus";
import { useIcon } from "@/hooks/web/useIcon";
import { GroupOrgData } from "@/api/group/org/types";

const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<GroupOrgData>>,
    default: () => null
  },
  formSchema: {
    type: Array as PropType<FormSchema[]>,
    default: () => []
  }
})

const rules = reactive({
})

const { register, methods, elFormRef } = useForm({
  schema: props.formSchema
})

const tableData = ref<Recordable>([]);

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    const { setValues } = methods
    setValues(currentRow)
    const arr = currentRow.arr.split(",");
    arr.forEach(v => {
      tableData.value.push({ orgId: v })
    })
  },
  {
    deep: true,
    immediate: true
  }
)

const getFormDataCustomer = async(): Promise<GroupOrgData> => {
  const data = (await methods.getFormData()) as GroupOrgData;
  const orgIdArr = tableData.value.map(d => d.orgId);
  if (orgIdArr.length > 0) {
    data.arr = orgIdArr.join(",");
  }
  return data;
}

defineExpose({
  elFormRef,
  getFormData: getFormDataCustomer
})

const handleDeleteRow = (scope) => {
  tableData.value.splice(scope.$index, 1);
}
const handleAddRow = () => {
  tableData.value.push({ orgId: '' });
}

const icons = {
  plusIcon: useIcon({ icon: 'ph:plus-bold' })
}
</script>

<template>
  <Form :rules="rules" @register="register">
    <template #arr>
      <el-table :data="tableData" :border="false" style="width: 100%">
        <el-table-column label="组织ID" prop="orgId">
          <template #default="scope">
            <el-input v-model="scope.row.orgId" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="70">
          <template #default="scope">
            <el-button link @click="handleDeleteRow(scope)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button style="margin-top: 10px" :icon="icons.plusIcon" type="primary" @click="handleAddRow">添加组织
      </el-button>
    </template>
  </Form>
</template>
